// MainWindow.cs created with MonoDevelop
// User: dantes at 8:54 PM 5/26/2008
//
using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Gtk;

public partial class MainWindow: Gtk.Window
{	
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
		//
		LblTitle.Icon = HollyLibrary.GraphUtil.pixbufFromStock("gtk-yes", Gtk.IconSize.Button);
		//adauga formatele
		String[] formats = new String[]{"MP3", "AVI"};
		CmbFormat.List.Items.AddRange( formats );
		CmbFormat.List.SelectedIndex = 0;
		GtkThreadeSleep( 100 );
	}
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}

	protected virtual void OnBtnAddClicked (object sender, System.EventArgs e)
	{
		AddUrl();
	}
	
	private void AddUrl( )
	{
		String url = TxtUrl.Text.Trim();
		if( !url.Equals("") )
		{
			LstUrls.Items.Add( url );
			TxtUrl.Text = "";
			TxtUrl.GrabFocus();
		}
	}

	protected virtual void OnTxtUrlKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args)
	{
		if( args.Event.Key == Gdk.Key.Return )
			AddUrl();
	}

	protected virtual void OnBtnIesireClicked (object sender, System.EventArgs e)
	{
		Gtk.Application.Quit();
	}

	protected virtual void OnBtnDownloadClicked (object sender, System.EventArgs e)
	{
		BtnAdd.Sensitive      = false;
		BtnDownload.Sensitive = false;
		BtnIesire.Sensitive   = false;
		LstUrls.Sensitive     = false;
		WebClient wb   = new WebClient();
		wb.DownloadProgressChanged += DownloadProgresChanged;
		//start downloading
		Progres.Adjustment.Lower = 0;
		Progres.Adjustment.Value = 0;
		Progres.Adjustment.Upper = LstUrls.Items.Count;
		//
		foreach( object item in LstUrls.Items )
		{
			String url     = item.ToString();
			//
			String content = getHtml( url );
			//
			String title   = Cauta( content, "<title>","</title>" )[0];
			title = title.Replace("YouTube - ","");
			//
			LblStatus.Text = title;
			//
			String videoid = Cauta( content, "\"video_id\": \"", "\"" )[0];
			String videol  = Cauta( content, " \"l\": "    , ","  )[0];
			String videot  = Cauta( content, "\"t\": \""   , "\"" )[0];
			
			String flvurl  =  "http://www.youtube.com/get_video.php?";
			flvurl        += "video_id=" + videoid + "&l=" + videol + "&t=" + videot;
			Console.WriteLine( flvurl );
			//download flvu
			wb.DownloadFileAsync( new Uri( flvurl ), "temp.flv" );
			//wait for file to download
			while( wb.IsBusy ) { Application.RunIteration(); }
			//converteste flvul in formatul ales
			String file_name      = title + "." + CmbFormat.Text;
			//de inlocuit apostroafele si ghilimelele din file_name
			file_name             = file_name.Replace("'","").Replace("\"","");
			String convert_string = "ffmpeg -i temp.flv -y '"+file_name+"'";
			Console.WriteLine( convert_string );
			
			
			Process proc          =  Process.Start( convert_string );
			while( !proc.HasExited )
			{
				ProgresConvert.Pulse();
				//System.Threading.Thread.Sleep(100);
				GtkThreadeSleep( 100 );
				Application.RunIteration();
			}
			ProgresConvert.Fraction = 0;
			//proc.WaitForExit();
			Console.WriteLine("am terminat!");
			//sterge flv-ul
			File.Delete( "temp.flv" );
			//muta fisierul generat in directorul ales
			File.Move( file_name, CmbFolder.SelectedPath + "/" + file_name );
			//updateste progresbaru
			Progres.Adjustment.Value++;
		}
		LstUrls.Items.Clear();
		BtnAdd.Sensitive      = true;
		BtnDownload.Sensitive = true;
		BtnIesire.Sensitive   = true;
		LstUrls.Sensitive     = true;
	}
	
	private void GtkThreadeSleep( int milisec )
	{
		DateTime now    = DateTime.Now;
		TimeSpan dif    = now.Subtract( DateTime.Now );
		int miliseconds = 0;
		while( miliseconds <= milisec )
		{
			Application.RunIteration();
			dif         = now.Subtract( DateTime.Now );
			int msec    = dif.Milliseconds;
			msec += ( dif.Seconds * 1000 );
			msec += ( dif.Minutes * 1000 * 60 );
			msec += ( dif.Hours   * 1000 * 24 * 60 );
			miliseconds += Math.Abs( msec );
		}
	}
	
	private void DownloadProgresChanged( object sender, DownloadProgressChangedEventArgs args )
	{
		Gdk.Threads.Enter();
		ProgresDownload.Adjustment.Lower = 0;
		ProgresDownload.Adjustment.Upper = 100;
		ProgresDownload.Adjustment.Value = args.ProgressPercentage;
		Gdk.Threads.Leave();
	}
	
	private List<String> Cauta( String content, String start, String end )
	{
		List<String> ret = new List<String>();
		String new_text  = content;
		while( new_text.IndexOf( start ) != -1 )
		{
			new_text     = new_text.Substring( new_text.IndexOf( start ) + start.Length );
			int poz_end  = new_text.IndexOf( end );
			String slice = new_text.Substring(0, poz_end );
			ret.Add( slice );
			new_text     = new_text.Substring( poz_end + end.Length );
		}
		return ret;
	}
	
	private String getHtml( String url )
	{
		StringBuilder sb  = new StringBuilder();

		// used on each read operation
		byte[]        buf = new byte[8192];

		// prepare the web page we will be asking for
		HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create( url);

		// execute the request
		HttpWebResponse response = (HttpWebResponse)
		request.GetResponse();

		// we will read data via the response stream
		Stream resStream = response.GetResponseStream();

		string tempString = null;
		int    count      = 0;

		do
		{
			// fill the buffer with data
			count = resStream.Read(buf, 0, buf.Length);

			// make sure we read some data
			if (count != 0)
			{
				// translate from bytes to ASCII text
				tempString = Encoding.ASCII.GetString(buf, 0, count);

				// continue building the string
				sb.Append(tempString);
			}
		}
		while (count > 0); // any more data to read?
		return sb.ToString();
	}

	protected virtual void OnLstUrlsRowActivated (object o, Gtk.RowActivatedArgs args)
	{
			LstUrls.Items.Remove( LstUrls.SelectedItem );
	}
	
}